<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="renderer" content="webkit" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black" />
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="format-detection" content="telephone=no" />
		<title>药品清单</title>
		<link rel="stylesheet" href="../../../../res/layui/css/layui.css" />
		<link rel="stylesheet" href="../../../../res/css/common/font-awesome.min.css" media="all">
		<link rel="stylesheet" href="../../../../res/layui-config/css/app.css" media="all">
		<link rel="stylesheet" type="text/css" href="../../../../res/css/material-list/index.css" />
		<link rel="stylesheet" type="text/css" href="../../../../res/css/material-list/row.css" />
		<script src="../../../../res/js/common/jquery-1.11.2.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../../../res/js/material-list/index.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../../../res/js/common/parameter.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body class="childBody">
		<section class="layui-col-md10">
			<div class="layui-card">
				<div class="card-top css-transition kit-table">
					<form class="layui-form" lay-filter="kit-search-form">
						<!-- 左上角的两个按钮 -->
				        <div class="kit-table-header">
				        	<div class="kit-search-btns" style="height: 30px;line-height: 30px;margin-left: 10px;font-size: 16px">
				        		药品：<font style="color: #DC2D00;" id="pmcName">计划名称</font>
				            </div>
				            <div class="kit-search-inputs">
				                <div class="kit-search-keyword">
				                    <input type="text" class="layui-input" id="serach-one" placeholder="药材.." onKeyUp="lockInput(this,'serach-two')"/>
				                    <button lay-submit lay-filter="search1"><i class="layui-icon">&#xe615;</i></button>
				                </div>
				                <div class="kit-search-more" id="kit-search-more-one">更多筛选<i class="layui-icon">&#xe61a;</i></div>
				            </div>
				        </div>
				        <!-- 搜索扩展工具条 -->
				        <div class="kit-search-mored layui-anim layui-anim-upbit" id="kit-search-mored-one">
				            <div class="kit-search-body">
				                <div class="layui-form-item">
				                    <label class="layui-form-label">药品名称</label>
				                    <div class="layui-input-block">
				                        <input type="text" name="drugName" id="serach-two" placeholder="搜索关键字.." autocomplete="off" class="layui-input" onKeyUp="lockInput(this,'serach-one')">
				                    </div>
				                </div>
				                <div class="layui-form-item">
					                <label class="layui-form-label">类型</label>
					                <div class="layui-input-block">
					                    <select name="dtId" class="drug-type">
					                      <option value=""></option>
					                    </select>
					                </div>
				                </div>
				                <div class="layui-form-item">
				                    <div class="layui-inline">
				                        <label class="layui-form-label">范围</label>
				                        <div class="layui-input-block">
					                        <div class="layui-input-inline" style="width: 100px;">
					                            <input type="text" name="priceMin" placeholder="￥" autocomplete="off" class="layui-input" maxlength="6" onKeyUp="amount(this)">
					                        </div>
					                        <div class="layui-form-mid">-</div>
					                        <div class="layui-input-inline" style="width: 100px;">
					                            <input type="text" name="priceMax" placeholder="￥" autocomplete="off" class="layui-input" maxlength="6" onKeyUp="amount(this)">
					                        </div>
				                        </div>
				                    </div>
				                </div>
				            </div>
				            <div class="kit-search-footer">
				                <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary kit-btn reset-btn">重置</button>
				                <button lay-submit lay-filter="search1" class="layui-btn layui-btn-sm kit-btn">确定</button>
				            </div>
				        </div>
			        </form>
					<div class="layui-card-body">
						<div id="toolbar">
							<div class="layui-inline">
								<button type="button" class="layui-btn layui-btn-sm add" title="筛选原材料">
									<i class="layui-icon">&#xe608;</i> 添加药品
								</button>
								<div class="layui-inline" style="margin-left: 20px;">总数量：<span style="color: #0000A0" id="allAmount">0</span></div>
						  	</div>
						</div>
						<div id="tableRes" class="table-overlay" style="margin: 0px auto">
							<div class="card-body-left">
								<div class="scroll-wrap">
									<ul class="down-ul">
										<p class="li-title">药品所需原料清单（list）</p>
									</ul>
								</div>
							</div>
							<div id="tableRes" class="card-body-right">
								<table id="dataTable1" lay-filter="dataTable1" class="layui-hide"></table>
							</div>
						</div>
						<div id="action" class="text-center">
							<button type="button" name="btnSave" class="layui-btn layui-btn-sm" data-type="save"><i class="fa fa-floppy-o fa-lg"></i> 保存</button>
							<button type="close" name="close" data-type="close" class="layui-btn layui-btn-sm layui-btn-primary"><i class="fa fa-times-circle-o" aria-hidden="true"></i> 放弃</button>
						</div>
					</div>
				</div>

				<div class="card-down css-transition kit-table">
					
					<form class="layui-form" lay-filter="kit-search-form">
						<!-- 左上角的两个按钮 -->
				        <div class="kit-table-header">
				        	<div class="kit-search-btns" style="height: 30px;line-height: 30px;margin: 0px 15px;font-size: 16px">
				        		药品筛选
				            </div>
				            <div class="kit-search-inputs">
				                <div class="kit-search-keyword">
				                    <input type="text" class="layui-input" id="serach-three" placeholder="药品.." onKeyUp="lockInput(this,'serach-four')"/>
				                    <button lay-submit lay-filter="search2"><i class="layui-icon">&#xe615;</i></button>
				                </div>
				                <div class="kit-search-more" id="kit-search-more-two">更多筛选<i class="layui-icon">&#xe61a;</i></div>
				            </div>
				        </div>
						<!-- 搜索扩展工具条 -->
				        <div class="kit-search-mored layui-anim layui-anim-upbit" id="kit-search-mored-two">
				            <div class="kit-search-body">
				                <div class="layui-form-item">
				                    <label class="layui-form-label">药品名称</label>
				                    <div class="layui-input-block">
				                        <input type="text" name="drugName" id="serach-four" placeholder="搜索关键字.." autocomplete="off" class="layui-input" onKeyUp="lockInput(this,'serach-three')">
				                    </div>
				                </div>
				                <div class="layui-form-item">
					                <label class="layui-form-label">类型</label>
					                <div class="layui-input-block">
					                    <select name="dtId" class="drug-type">
					                      <option value=""></option>
					                    </select>
					                </div>
				                </div>
				                <div class="layui-form-item">
				                    <div class="layui-inline">
				                        <label class="layui-form-label">范围</label>
				                        <div class="layui-input-block">
					                        <div class="layui-input-inline" style="width: 100px;">
					                            <input type="text" name="priceMin" placeholder="￥" autocomplete="off" class="layui-input" maxlength="6" onKeyUp="amount(this)">
					                        </div>
					                        <div class="layui-form-mid">-</div>
					                        <div class="layui-input-inline" style="width: 100px;">
					                            <input type="text" name="priceMax" placeholder="￥" autocomplete="off" class="layui-input" maxlength="6" onKeyUp="amount(this)">
					                        </div>
				                        </div>
				                    </div>
				                </div>
				            </div>
				            <div class="kit-search-footer">
				                <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary kit-btn reset-btn">重置</button>
				                <button lay-submit lay-filter="search2" class="layui-btn layui-btn-sm kit-btn">确定</button>
				            </div>
				        </div>
				    </form>
					
					
					<div class="layui-card-body body-down">
						<div id="tableRes" class="table-overlay">
							<div class="card-body-left">
								<div class="scroll-wrap">
									<ul class="down-ul">
										<p class="li-title">药品清单（list）</p>
									</ul>
								</div>
							</div>
							<div id="tableRes" class="card-body-right">
								<table id="dataTable2" lay-filter="dataTable2" class="layui-hide" ></table>
							</div>
							<div id="action" class="text-center">
								<button type="button" name="btnConfirm" class="layui-btn layui-btn-sm btnConfirm" data-type="confirm"><i class="fa fa-check-circle-o fa-lg" aria-hidden="true"></i> 确定</button>
								<button type="reset" name="btnCancel" class="layui-btn layui-btn-sm layui-btn-primary"><i class="fa fa-chevron-circle-left" aria-hidden="true"></i> 取消</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</section>
		<script>
			//文本框只能输入金额
		    function amount(th){
		        var regStrs = [
		            ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0
		            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
		            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
		            ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
		        ];
		        for(i=0; i<regStrs.length; i++){
		            var reg = new RegExp(regStrs[i][0]);
		            th.value = th.value.replace(reg, regStrs[i][1]);
		        }
		    }
			//搜索框同步输入
			function lockInput(obj,id){
				$("#"+id).val($(obj).val());
			}
		</script>
		<script src="../../../../res/layui/layui.all.js"></script>
		<script type="text/html" id="img">
			<img style="height:100%;height:30px;" onclick="getPathOver(this)" src="../../../../{{ d.drugPictrue}}">
		</script>
		<script type="text/javascript">
			function getSession(){
				var admin = null;
				$.ajax({ 
		        	url:"../../../../admin/getSession.action",
	                type:'post',
	                async:false,
	                dataType:'json',
	                success:function(mes){
	                	if (mes!=null && mes!="") {
	                		admin = mes;
						} else {
							location.href = "../../../../admin/login.html";
						}
	                },
	                error: function(){
	                	location.href = "../../../../admin/login.html";
	                }
	        	});
				return admin;
			}
			//准备视图对象
			var pmcId = getParameter("id");
			$("#pmcName").text(getParameter("name"));
			window.viewObj = null;
			var newData = new Array();//第一个表格的所有数据
			$.ajax({
				url: "../../../../pmcDetails/findAll.action", //json文件位置
				data: {"page":1,"limit":10000,"pmcId":pmcId},
				type: "post",
				async: false,
				dataType: "json", //返回数据格式为json
				success: function(res) { //请求成功完成后要执行的方法
					layui.each(res.data, function(index, data) {
						res.data[index].state=1;
						res.data[index].checkDisabled == true;
					});
					viewObj = res;
					newData = res.data;
				}
			});
			var arr1 = new Array();//选中的数据
			var arr2 = new Array();//表格的数据
			//layui 模块化引用
			layui.use(['table', 'layer', 'element', 'jquery', 'form'], function(table, layer, element, $, form) {
				// data模式
				var $ = layui.$, table = layui.table, form = layui.form, layer = layui.layer;
				
				autoHeight();
				
				//数据表格实例化			
				var layTableId1 = "layTableId1";
				var tableElems;
				var tableIns1 = table.render({
					elem: '#dataTable1',
					id: layTableId1,
					data: viewObj.data,
					height: 'full-178',
					page: true,
					limits: [5,10,20,30,40,50,60,70,80],
					cols: [
						[
							{title: '序号',type: 'numbers'},
							{field: 'drugId',title: '药品ID'},
							{field: 'drugName',title: '药品名称（name）'},
							{field: 'pdAmount',title: '数量（amount）',width: 200,edit: 'text',sort: true},
							{field: 'dtName',title: '类型',width: 90},
							{field: 'drugUnit',title: '单位（unit）',width: 85,align: 'center'},
							{field: 'drugProp',title: '种类（type）',width: 150},
							{field: 'tempId',title: '操作',width: '15%',
								templet: function(d) {
									return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="' + d.tempId +
										'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
								}
							}
						]
					],
					done: function(res, curr, count) {
						tableElems = this.elem.next('.layui-table-view');
						$("#allAmount").text(0);
						//计算数量
						function count(o){
							var amount = o.val() =='' ? 0 : parseInt(o.val());
							o.parents('tr').siblings().find('td[data-field="pdAmount"]').each(function(){
								amount += parseInt($(this).text());
							});
							$("#allAmount").text(amount);
						}
						
						$("[data-field = 'pdAmount']").not(":first").each(function(){
							$("#allAmount").text(parseInt($("#allAmount").text())+parseInt($(this).text()));
							$(this).css({
								"color": "#0000A0"
							}).on('focus', '.layui-table-edit', function(){
								if ($(this).prop('maxlength') == -1) $(this).prop('maxlength', 5);
							}).on('blur', '.layui-table-edit', function(){
								var o = $(this);
								if (o.val().length < 1) o.val(1);
								count(o);
							}).on('change', '.layui-table-edit', function() {
								if ($(this).val().length < 1) $(this).val(1);
								getAmount();
							}).on('keyup', '.layui-table-edit', function() {
								var o = $(this);
								o.val(o.val().replace(/[^0-9]*$/, ""));//正整数
								o.val(o.val().replace(/^[0]+[0-9]*$/gi, ""));//第一位不能为零
								count(o);
							});
					  	});
						
						$("[data-field = 'drugProp']").children().each(function(){
						    if($(this).text() == '1'){
						    	$(this).text("处方药");
						    } else if ($(this).text() == '0') {
						    	$(this).text("非处方药");
						    }
					  	});
						$(".mat").remove();
						getAmount();
					}
				});
				function getAmount(){
					tableElems.find("tr").find('td[data-field="pdAmount"]').each(function(index){
						var o = $(this);
						$(".amount").text("0");
						var drugId = tableElems.find('tr[data-index="' + index + '"]').find('td[data-field="drugId"]').text();
						$.post("../../../../pmcDetails/checkInv.action",{"drugId": drugId},function(mes){
							$.each(mes,function(index,item){
								var bln = false;
								$(".mat").each(function(indexs,items){
									if (items.id == item.miId) {
										$(items).find(".amount").text(parseInt($(items).find(".amount").text())+parseInt(item.mlAmount)*parseInt(o.text()));
										bln = true;
										return
									}
								});
								if (!bln) {
									$("<li />", {
										'id': item.miId,
										'text': item.matName,
										'class': "mat"
									}).insertAfter($(".li-title").eq(0));
									$("#"+item.miId).append("<span class='li-closes'><span class='amount'>"+parseInt(item.mlAmount)*parseInt(o.text())+"</span> / "+item.miAmount+"</span>");
								}
							});
						},"json");
					});
				}
				
				//点击排序重新渲染表格
		        table.on('sort(dataTable1)', function(obj){
		        	tableIns1.reload({
						data: newData
					});
		        });
				
				//监听搜索表单提交
		        form.on('submit(search1)', function(data) {
		        	layer.confirm('你还没有保存确定要执行吗？', function(index) {
		        		layer.close(index);
		        		data.field["page"]=1;
			        	data.field["limit"]=10000;
			        	data.field["pmcId"]=pmcId;
			        	var viewObjs = null;
			        	$.ajax({
							url: "../../../../pmcDetails/findAll.action", //json文件位置
							data: data.field,
							type: "post",
							async: false,
							dataType: "json", //返回数据格式为json
							success: function(res) { //请求成功完成后要执行的方法
								viewObjs = res;
							}
						});
			            //带条件查询
			            tableIns1.reload({
			            	data: viewObjs.data
			            });
			            arr1 = [];
			            newData = [];
			            for (x in viewObj.data) {
			            	newData.push(viewObj.data[x])
			            }
			            $('#kit-search-mored-one').hide();
		        	});
		            return false;
		        });
				
		     	//表单渲染
		        form.render(null, 'kit-search-form');
				
		      	//更多筛选点击事件
		        $('#kit-search-more-one').on('click', function() {
		            $('#kit-search-mored-one').toggle();
		        });
				
				//定义事件集合
				var active = {
					save: function() {
	                    var bln = true;
	                    $.each($(".li-closes"),function(index,item){
	    					var o = $(this).text().split("/");
	    					if (parseInt(o[0])>parseInt(o[1])) {
	    						layer.msg("原材料库存不足！");
	    						bln = false;
	    					}
	    				});
	                    if (bln) {
	                    	layui.each(newData, function(index, item) {
	                    		addOrUpdate(item);
	                    	});
	                    	save({"pmcId": pmcId,"pmcAmount": $("#allAmount").text()});
	                    }
					},
					confirm: function() {
						newData = [];
						for(var i=0;i<viewObj.data.length;i++){
							newData.push(viewObj.data[i]);
						}
						for (var j=0;j<arr1.length;j++) {
							newData.unshift(arr1[j]);
						};
						tableIns1.reload({
							data: newData
						});
					},close: function() {
						closeLayer();
					}
				}

				//激活事件
				var activeByType = function(type, arg) {
					if (arguments.length === 2) {
						active[type] ? active[type].call(this, arg) : '';
					} else {
						active[type] ? active[type].call(this) : '';
					}
				}

				//注册按钮事件
				$('.layui-btn[data-type]').on('click', function() {
					var type = $(this).data('type');
					activeByType(type);
				});
				
				//监听工具条
				table.on('tool(dataTable1)', function(obj) {
					var data = obj.data,
						event = obj.event,
						tr = obj.tr; //获得当前行 tr 的DOM对象;
					switch (event) {
						case "del":
							layer.confirm('真的删除行么？', function(index) {
								//obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
								layer.close(index);
								for (var i = 0, row; i < newData.length; i++) {
									row = newData[i];
									if (data.drugId == row.drugId) {
										if (row.state==1) {
											var arr3 = new Array();
											for (var j = 0; j < viewObj.data.length; j++) {
												if (row.drugId != viewObj.data[j].drugId) {
													arr3.push(viewObj.data[j]);
												} else {
													addOrUpdate({"pdId":viewObj.data[j].pdId,"isva":0});
												}
											}
											viewObj.data = arr3;
										} else {
											removeOne(row.drugId);
										}
										newData.splice(i, 1);
										break;
									}
								}
								tableIns1.reload({
									data: newData
								});
							});
						break;
					}
				});

				
				
				
				var layTableId2 = "table2";
				var tableElem = "";
				var admin = getSession();
		    	if (admin==null) return;
				var tableIns2 = table.render({
					elem: '#dataTable2',
					id: layTableId2,
					height: 'full-145',
					where: {"comId": admin.comId},
					url: "../../../../drug/showChecked.action",
					page: true,
					limits: [5,10,20,30,40,50,60,70,80],
					cols: [
						[
							{type: 'checkbox',fixed: true},
							{title: '序号',type: 'numbers'},
							{field: 'drugId',title: 'ID',width: 150},
			                {field: 'drugName',title: '药名'},
			                {field: 'drugUnit',title: '单位',width: 80},
			                {field: 'dtName',title: '类型',width: 90},
			                {field: 'drugProp',title: '属性',width: 90},
			                {field: 'drugPictrue',title: '图片',width: 60,templet:'#img'},
			                {field: 'drugPrice',title: '价格（元）',width: 120,sort: true}
						]
					],
					done: function(res, curr, count) {
						tableElem = this.elem.next('.layui-table-view');
						count || tableElem.find('.layui-table-header').css('overflow', 'auto');
						layui.each(table.cache[layTableId2], function(index, data) {
							$("[data-field = 'drugPictrue']").children().each(function(){
			                	var obj = $(this);
			                	obj.find('img').on("error", function () {
			                		obj.text('');
			                	});
			                	obj.find('img').on("load", function () {
			                		obj.find('img').mouseover(function() {
				                		layer.tips("点击查看", this, {
			                            	tips: [3, "#4794ec"],time: 1000
			                          	});
			                      	});
			                	});
						  	});
							$("[data-field = 'drugProp']").children().each(function(){
							    if($(this).text() == '1'){
							    	$(this).text("处方药");
							    } else if ($(this).text() == '0') {
							    	$(this).text("非处方药");
							    }
						  	});
							for (var j = 0; j < newData.length; j++) {
								if (newData[j].drugId == data.drugId) {
									res.data[index]["LAY_CHECKED"] = true;
									res.data[index].checkDisabled = true;
									tableElem.find('tr[data-index="' + index + '"]').find('input[name="layTableCheckbox"]').attr({name: 'layTableCheckbox_disabled',disabled: 'disabled'}).next().removeClass('layui-form-checked');
									tableElem.find('tr[data-index="' + index + '"]').find('td').css({"color":"#C0C0C0"});
									return;
								} else {
									res.data[index].checkDisabled = false;
								}
							}
							for (var i = 0; i < arr1.length; i++) {
								if (res.data[index].drugId == arr1[i].drugId) {
									res.data[index]["LAY_CHECKED"] = true;
									tableElem.find('tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true).next().addClass('layui-form-checked');
								}
							}
						});
						var checkStatus = table.checkStatus(layTableId2);
						if (checkStatus.isAll) {
							var count = 0;
							for (var i = 0; i < checkStatus.data.length; i++) {
								if (!checkStatus.data[i].checkDisabled) count++;
							}
							var obj = tableElem.find('th[data-field="0"] input[type="checkbox"]');
							if (count>0) {
								obj.prop('checked', true).next().addClass('layui-form-checked');
							} else {
								obj.prop('checked', false).next().removeClass('layui-form-checked');
							}
						}
						form.render();
					}
				});
				
				$.ajax({ 
					url:"../../../../drugType/showList.action",
                    type:'post',//method请求方式，get或者post
                    async:false,//同步
                    dataType:'json',//预期服务器返回的数据类型
                    success:function(mes){//res为相应体,function为回调函数
                    	//循环添加类型搜索框内的数据
                    	$.each(mes.types,function(index,item){
                    		$(".drug-type").append("<option value="+item.dtId+">"+item.dtName+"</option>");
                    	});
                    	//渲染类型搜索框内的下拉框
                    	renderForm();
                    }
                 });
				
				//点击排序重新渲染表格
		        table.on('sort(dataTable2)', function(obj){
		        	tableIns2.reload();
		        });
				
				//监听搜索表单提交
		        form.on('submit(search2)', function(data) {
		            //带条件查询
		            tableIns2.reload({
		                where: data.field
		            });
		            $('#kit-search-mored-two').hide();
		            return false;
		        });
				
		      	//表单渲染
		        form.render(null, 'kit-search-form');
		      	
		        //更多筛选点击事件
		        $('#kit-search-more-two').on('click', function() {
		            $('#kit-search-mored-two').toggle();
		        });
				
				//复选框点击事件
				table.on('checkbox(dataTable2)', function(obj) {
					if (obj.checked == true) {
						if (obj.type == 'one') {
							addRow(obj.data);
							arr1.push(obj.data);
							arr1[arr1.length-1]['state']=0;
							arr1[arr1.length-1]['pdAmount']=1;
							arr1[arr1.length-1]['pmcId']=pmcId;
							arr1[arr1.length-1]['checkDisabled']=false;
						} else {
							arr2 = table.cache[layTableId2];
							for (var i = 0; i < arr2.length; i++) {
								var count = 0;
								for (var j = 0; j < arr1.length; j++) {
									if (arr2[i].drugId == arr1[j].drugId) {
										count++;
									}
								}
								if (count === 0&&!arr2[i].checkDisabled) {
									addRow(arr2[i]);
									arr2[i]['state']=0;
									arr2[i]['pdAmount']=1;
									arr2[i]['pmcId']=pmcId;
									arr2[i]['checkDisabled']=false;
									arr1.push(arr2[i]);
								}
							}
							arr3 = arr1;
						}
					} else {
						if (obj.type == 'one') {
							if (!obj.data.checkDisabled) {
								removeOne(obj.data.drugId);
							}
						} else {
							arr2 = table.cache[layTableId2];
							for (var i = 0; i < arr2.length; i++) {
								if (!arr2[i].checkDisabled) {
									removeOne(arr2[i].drugId);
								}
							}
						}
					}
					console.log(arr1);
				});
				function closeLayer(){
				    //当你在iframe页面关闭自身时
					var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
					parent.layer.close(index); //再执行关闭   
				}
				function save(data){
					$.ajax({ 
    		        	url: '../../../../pmc/addOrUpdate.action',
    		        	data: JSON.stringify(data),
    		        	cache: false,//同步
                        type: 'post',//method请求方式，get或者post
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success:function(mes){
                        	layer.msg(mes.msg);
                        	if (mes.status==1) {
                        		setTimeout(function () {
                        			closeLayer();
                            		window.parent.location.reload();
                            	},1000);
                        	}
                        }
                    });
				}
				function addOrUpdate(data){
					$.ajax({ 
    		        	url: '../../../../pmcDetails/addOrUpdate.action',
    		        	data: JSON.stringify(data),
    		        	cache: false,//同步
                        type: 'post',//method请求方式，get或者post
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json'
                    });
				}
				form.on('select(mat-type)', function(data){
					//带条件查询
		            tableIns.reload({
		                where: data.field,
		                page: { curr: 1 }
		            });
		            $('.kit-search-mored').hide();//关闭搜索层
		            return false;
				})
				//重新渲染表单
			  	function renderForm(){ 
		  			layui.use('form', function(){ 
			  			var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加() 
			  			form.render(); 
		  			}); 
		  		}
				
				//窗口自适应
				function autoHeight() {
					setHeight();
				    window.onresize = function() {
				    	setHeight();
					}
				}
				
				function setHeight() {
					var h = document.body.clientHeight && document.documentElement.clientHeight - 165; //窗口高度
				    $(".layui-card").height(h+135);
					$(".card-body-left").eq(0).height(h-15);
					$(".card-body-left").eq(1).height(h+18); 
				}
				
				//移除数组内重复的元素
				function removeOne(arrId) {
					var arr3 = new Array();
					for (var i = 0; i < arr1.length; i++) {
						if (arr1[i].drugId == arrId) {
							removeRow(arr1[i].drugId);
						} else {
							arr3.push(arr1[i]);
						}
					}
					arr1 = arr3;
				}
				
				function changeState(rowId) {
					var objStr = tableElem.find("td[data-field='drugId']");
					for (var i = 0; i < objStr.length; i++) {
						if (objStr[i].innerText == rowId) {
							tableElem.children().find('.layui-table-fixed input[type="checkbox"]').eq(i+1).next().click();
							tableElem.find('.layui-table-fixed input[type="checkbox"]').eq(i+1).next().removeClass('layui-form-checked');
						}
					}
				}
				
				function addClose(obj) {
					obj.append("<span class='li-close'>×</span>");
					obj.find(".li-close").on("click", function() {
						changeState(obj.prop("id"));
						removeOne(obj.prop("id"));
					});
				}

				function addRow(data) {
					$("<li />", {
						'id': data.drugId,
						'text': data.drugName,
						'class': "new-item "
					}).insertAfter($(".li-title").eq(1));
					addClose($("#" + data.drugId));
				}
				
				function removeRow(id) {
					var removePoint = $(".down-ul").eq(1).find("#" + id);
					removePoint.removeClass("new-item").addClass("remove-item");
					setTimeout(function() {
						$(".down-ul").eq(1).find(".remove-item").remove();
					}, 480);
				}
				
				$(".add").on("click",function(){
					$(".card-top,.card-down").addClass("css-showTrans").removeClass("css-closeTrans");
					$(".down-ul").eq(1).find(".old-item").remove();
					for (var i = 0; i < newData.length; i++) {
						$(".down-ul").eq(1).append('<li class="old-item">'+newData[newData.length-1-i].drugName+'</li>');
					}
					tableIns2.reload();
				});
				$(".btnConfirm").on("click",function(){
					$(".card-top,.card-down").removeClass("css-showTrans").addClass("css-closeTrans").removeClass("css-closeTrans");
					$(".down-ul").eq(1).find(".new-item").remove();
				});
				$("button[name=btnCancel]").on("click",function(){
					$(".card-top,.card-down").removeClass("css-showTrans").addClass("css-closeTrans").removeClass("css-closeTrans");
				});
			});
			
			/**
			*鼠标进入时
			*/
			function getPathOver(obj){
				$("body").append('<div id="layer"></div><img id="pic" src="#" style="width:280px;height:280px;display:none;z-index:999;border-radius: 2px;margin: auto;position: absolute;top: 0px;bottom: 0px;left: 0px;right: 0px;border: 1px solid #424242"/>');
				$("#layer").addClass("layer").fadeIn("slow");
				$("#layer").click(function(){
					getPathOut();
				});
				$("#pic").fadeIn("slow");
				$('#pic').attr({"src":obj.src});
			}
			/**
			*鼠标退出时
			*/
			function getPathOut(){
				$("#layer").fadeOut("slow");
				$("#pic").fadeOut("slow");
			}
			
			//ajax加载动画
		    $(function () {
	            $.ajaxSetup({
	                layerIndex:-1,
	                beforeSend: function () {
	                    this.layerIndex = layer.load(1, { shade: [0.8, '#ffffff'] });
	                },
	                complete: function () {
	                    layer.close(this.layerIndex);
	                },
	                error: function () {
	                    layer.alert('部分数据加载失败，可能会导致页面显示异常，请刷新后重试', {
	                        skin: 'layui-layer-molv'
	                       , closeBtn: 0
	                       , shift: 4 //动画类型
	                    });
	                }
	            });
	        });
		</script>
	</body>
</html>
